#!/bin/bash

function usage
{
  echo "Usage:"
  echo "  rerun.sh \"Result string\""
}

if [ $# -ne 1 ]; then
  echo "Incorrect options passed"
  usage
  exit 1
fi

[ -z "${DBNAME+set}" ] && read -p "DB Name:" DBNAME
[ -z "${DBUSER+set}" ] && read -p "DB Username:" DBUSER
[ -z "${DBPASSWD+set}" ] && read -sp "DB Password:" DBPASSWD

IFS=, read DDHASH FSHASH DBHASH EXPERIMENTNAME TESTFILENAME FSFILESIZE DBFILESIZE DDTIMETAKEN FSTIMETAKEN DBTIMETAKEN FSHASHMATCH DBHASHMATCH DBSIZEMATCH TESTLABEL TESTSTARTDATE TESTSTARTTIME <<< "$1"

DBRESULT=$(bsqldb -S hdcsql -U "$DBUSER" -P "$DBPASSWD" -D "$DBNAME" -q -t , <<< "SELECT FILESIZE, SHA1HASH FROM dbo.ExperimentDataFiles WHERE Filename COLLATE Latin1_General_CI_AS =\"${TESTFILENAME}\"")

if [ $(wc -l <<< "$DBRESULT") -ne 1 ]; then
  echo "Too many results returned to work out whether file now matches"
  echo Results:
  #  DBRESULT=$(bsqldb -S hdcsql -U "$DBUSER" -P "$DBPASSWD" -D "$DBNAME" -t , <<< "SELECT * FROM dbo.ExperimentDataFiles WHERE Filename COLLATE Latin1_General_CI_AS =\"${TESTFILENAME}\"")
  echo "$DBRESULT"
  exit 1
fi

# Get new DBFILESIZE and DBHASH
IFS=, read DBFILESIZE DBHASH <<< "$DBRESULT"

# Check hashes are correct
if [ "$DDHASH" = "$DBHASH" ]; then
  DBHASHMATCH=Match
else
  DBHASHMATCH=Mismatch
fi

if [ "$DDHASH" = "$FSHASH" ]; then
  FSHASHMATCH=Match
else
  FSHASHMATCH=Mismatch
fi

if [ "$FSFILESIZE" = "$DBFILESIZE" ]; then
  DBSIZEMATCH=Match
else
  DBSIZEMATCH=Mismatch
fi

# Print results to standard out
printf "%s,%s,%s,%s,%s,%.0f,%.0f,%.0f,%.0f,%.0f,%s,%s,%s,%s,%s,%s\n" $DDHASH $FSHASH $DBHASH $EXPERIMENTNAME $TESTFILENAME $FSFILESIZE $DBFILESIZE $DDTIMETAKEN $FSTIMETAKEN $DBTIMETAKEN $FSHASHMATCH $DBHASHMATCH $DBSIZEMATCH $TESTLABEL $TESTSTARTDATE $TESTSTARTTIME
